import mongoose from 'mongoose'
mongoose.Promise = Promise
const TokenSchema = new mongoose.Schema({
  name: String,
  token: String,
  expires_in: Number,
  meta: {
    createdAt: {
      type: Date,
      default: Date.now()
    },
    updatedAt: {
      type: Date,
      default: Date.now()
    }
  }
})
TokenSchema.pre('save', function (next) {
  this.isNew ? this.meta.createdAt = this.meta.updatedAt = Date.now() : this.meta.updatedAt = Date.now()
  next()
})
TokenSchema.statics = {
  async getAccessToken() {
    const token = await this.findOne({
      name: 'access_token'
    }).exec()
    if (token && token.token) {
      token.access_token = token.token
    }
    return token
  },
  async saveAccessToken(data) {
    let token = await this.findOne({
      name: 'access_token'
    }).exec()
    if (token) {
      token.token = data.access_token
      token.expires_in = data.expires_in
    } else {
      token = new Token({
        name: 'access_token',
        token: data.access_token,
        expires_in: data.expires_in
      })
      await token.save()
    }
  },
  async rmAccessToken(data) {
    let token = await this.findOne({
      name: 'access_token'
    }).exec()
    let delState = ''
    if (token) {
      delState = await Token.remove({
        name: 'access_token'
      }).exec()
    } else {
      delState = 'no accessToken alive'
    }
    return delState
  }
}
const Token = mongoose.model('Token', TokenSchema, 'Token')
export default Token
